package main

import (
	"io"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"encoding/json"
	"time"
)

func checkVersion(){
	conn, err := ConnectServer(server, "8888")
        if err != nil {
                log.Error("can not connect to update server %s:8888",server)
		return
        }
	defer conn.Close()
	log.Info("client version check")
	pk:=map[string]interface{}{"type":"3","version":version}
	req,_:=json.Marshal(pk)
	if err:=SendData(conn,req);err!=nil{
		log.Error("send data error <%v>",err)
		return
	}
	if rep := ReadData(conn);rep !=nil {
		log.Info(string(rep))
		var pk  map[string]interface{}
		err:=json.Unmarshal(rep,&pk)
		if err!=nil{
			log.Error("the server response protocol error")
			return
		}
		var url string
		var file string
		if filename,ok:=pk["filename"].(string);ok{
			url = "http://"+ server +":8887/" + filename
			file = filename
		}
		log.Info("---------------->",file)
		if len(url) == 0 {
			log.Info("no filename to update,exit")
			return
		}
		log.Info("find a new client version,download...")
		err=Download(url)
		if err == nil{
			if ok:=Update(file);ok==nil{
				log.Info("client update success, wait to exit")
				time.Sleep(2e9)
				os.Exit(0)
			}
		}
	}
	log.Info("no need update")
	return
}

func Download(url string) error {
	field := strings.Split(url, "/")
	filename := field[len(field)-1]
	res, err := http.Get(url)
	if err != nil {
		log.Error("cannot connect to update server <%v>", err)
		return err
	}
	if res.StatusCode != 200 {
		log.Critical("get the update file error, status code <%v>", res.StatusCode)
		return err
	}
	fd, err := os.Create("./update/"+filename)
	if nil != err {
		log.Error("cannot create file <%v>", err)
		return err
	}
	defer fd.Close()
	log.Info("start download..")
	n, err := io.Copy(fd, res.Body)
	if nil != err {
		log.Critical("download failed <%v>", err)
		return err
	}
	log.Info("download success, write %d byte", n)
	return nil
}

func Update(file string) error {
	//fd, err := os.OpenFile("tdclient", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0x755)
	pth, err := exec.LookPath("tar")
	if nil != err {
		log.Error("cannot find tar command")
		return err
	}
	_, err = exec.Command(pth, "xf", "./update/"+file).Output()
	if nil != err {
		log.Error("update error <%v>", err)
		return err
	}
	log.Info("update successed")
	return nil
}
